package com.ktjy.ktmall.dao.impl;

import com.ktjy.ktmall.dao.BaseDao;
import com.ktjy.ktmall.dao.TUserDao;
import com.ktjy.ktmall.entity.TUser;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class TUserImpl extends BaseDao implements TUserDao {
    @Override
    //查询所有用户信息
    public List<TUser> getUserList() {
        List<TUser> list = new ArrayList<>();
        String sql = "SELECT * FROM t_user";

        try (Connection conn = this.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                TUser user = new TUser();
                user.setId(rs.getLong("id"));
                user.setRoleId(rs.getLong("roleId"));
                user.setLoginName(rs.getString("loginName"));
                user.setPassword(rs.getString("password"));
                user.setSex(rs.getInt("sex")); // 假设 sex 字段是整数类型
                user.setIdentityCode(rs.getString("identityCode"));
                user.setEmail(rs.getString("email"));
                user.setMobile(rs.getString("mobile"));
                user.setEnabled(rs.getInt("enabled")); // 假设 enabled 字段是整数类型
                user.setCreateTime(rs.getTimestamp("create_time"));
                user.setUpdateTime(rs.getTimestamp("update_time"));
                list.add(user);
            }
        } catch (SQLException e) {
            // 记录异常信息
            e.printStackTrace();
            throw new RuntimeException("Failed to get user list", e);
        }

        return list;
    }

    //根据用户姓名查询所有用户信息
    @Override
    public TUser getUserByLoginName(String loginName) {
        TUser user = null;
        String sql = "SELECT * FROM t_user WHERE loginName = ?";

        try (Connection conn = this.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, loginName);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    user = new TUser();
                    user.setId(rs.getLong("id"));
                    user.setRoleId(rs.getLong("roleId"));
                    user.setLoginName(rs.getString("LoginName"));
                    user.setPassword(rs.getString("password"));
                    user.setSex(rs.getInt("sex")); // 假设 sex 字段是整数类型
                    user.setIdentityCode(rs.getString("identityCode"));
                    user.setEmail(rs.getString("email"));
                    user.setMobile(rs.getString("mobile"));
                    user.setEnabled(rs.getInt("enabled")); // 假设 enabled 字段是整数类型
                    user.setCreateTime(rs.getTimestamp("create_time"));
                    user.setUpdateTime(rs.getTimestamp("update_time"));
                }
            }
        } catch (SQLException e) {
            // 记录异常信息
            e.printStackTrace();
            throw new RuntimeException("Failed to get user by login name: " + loginName, e);
        }

        return user;    }

    //根据用户编号查询对应的用户信息
    @Override
    public TUser getUserById(long id) {
        TUser user = null;
        String sql = "SELECT * FROM t_user WHERE id = ?";

        try (Connection conn = this.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setLong(1, id);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    user = new TUser();
                    user.setId(rs.getLong("id"));
                    user.setRoleId(rs.getLong("roleId"));
                    user.setLoginName(rs.getString("loginName"));
                    user.setPassword(rs.getString("password"));
                    user.setSex(rs.getInt("sex")); // 假设 sex 字段是整数类型
                    user.setIdentityCode(rs.getString("identityCode"));
                    user.setEmail(rs.getString("email"));
                    user.setMobile(rs.getString("mobile"));
                    user.setEnabled(rs.getInt("enabled")); // 假设 enabled 字段是整数类型
                    user.setCreateTime(rs.getTimestamp("create_time"));
                    user.setUpdateTime(rs.getTimestamp("update_time"));
                }
            }
        } catch (SQLException e) {
            // 记录异常信息
            e.printStackTrace();
            throw new RuntimeException("Failed to get user by ID: " + id, e);
        }

        return user;
    }


    //添加用户信息
    @Override
    public boolean addUser(TUser user) {
        if (user == null) {
            return false;
        }
        String sql = "INSERT INTO t_user (loginName, password, sex, identityCode, email, mobile, enabled, create_time, update_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

        try (Connection conn = this.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, user.getLoginName());
            pstmt.setString(2, user.getPassword());
            pstmt.setInt(3, (int) user.getSex());
            pstmt.setString(4, user.getIdentityCode());
            pstmt.setString(5, user.getEmail());
            pstmt.setString(6, user.getMobile());
            pstmt.setInt(7, (int) user.getEnabled());
            pstmt.setTimestamp(8, user.getCreateTime());
            pstmt.setTimestamp(9, user.getUpdateTime());

            int rowsInserted = pstmt.executeUpdate();
            return rowsInserted > 0;
        } catch (SQLException e) {
            // 记录异常信息
            e.printStackTrace();
            throw new RuntimeException("Failed to add user", e);
        }
    }

    //修改用户信息
    @Override
    public void updateUser(TUser user) {
        if (user == null || user.getId() == 0) {
            System.out.println("User is null or ID is invalid, cannot update.");
            return;
        }

        String sql = "UPDATE t_user SET loginName = ?, password = ?, sex = ?, identityCode = ?, email = ?, mobile = ?, enabled = ?, update_time = ? WHERE id = ?";

        try (Connection conn = this.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, user.getLoginName());
            pstmt.setString(2, user.getPassword());
            pstmt.setInt(3, (int) user.getSex());
            pstmt.setString(4, user.getIdentityCode());
            pstmt.setString(5, user.getEmail());
            pstmt.setString(6, user.getMobile());
            pstmt.setInt(7, (int) user.getEnabled());
            pstmt.setTimestamp(8, user.getUpdateTime());
            pstmt.setLong(9, user.getId());

            int rowsUpdated = pstmt.executeUpdate();
            if (rowsUpdated > 0) {
                System.out.println("User updated successfully! User: " + user);
            } else {
                System.out.println("No user found with ID: " + user.getId());
            }
        } catch (SQLException e) {
            System.out.println("Failed to update user: " + user);
            throw new RuntimeException("Failed to update user", e);
        }
    }

    //删除用户信息
    @Override
    public void deleteUser(long id) {
        if (id <= 0) {
            System.out.println("Invalid user ID, cannot delete.");
            return;
        }

        String sql = "DELETE FROM t_user WHERE id = ?";

        try (Connection conn = this.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setLong(1, id);

            int rowsDeleted = pstmt.executeUpdate();
            if (rowsDeleted > 0) {
                System.out.println("User deleted successfully! ID: " + id);
            } else {
                System.out.println("No user found with ID: " + id);
            }
        } catch (SQLException e) {
            System.out.println("Failed to delete user with ID: " + id);
            throw new RuntimeException("Failed to delete user", e);
        }
    }

    //登录
    @Override
    public TUser login(String loginName, String password) {
      //首先验证该用户表当中是否有这个用户
        TUser user = getUserByLoginName(loginName);
        if (user != null && user.getPassword().equals(password)) {
            return user;
        } else {
            return null;
        }
    }
}
